<script lang="tsx" setup>
/**
 * 编码规则 - 表单
 */
import {convertEnumToList, DialogForm, processRequest} from "@/framework/index.ts";
import {nextTick, ref, watch} from "vue";
import {CodeTypeEnum, DateTypeEnum, RefreshDateTypeEnum} from "@/pages/system/code-rule/index.ts";
import {ElMessage, ElMessageBox} from "element-plus";

/**
 * 定义emits
 */
const emit = defineEmits<{
  (e: "confirm"): void
}>()

/**
 * 显示
 */
const id = ref()
const dialogFormRef = ref()
const dialogFormModel = {
  title: "编码规则表单",
  width: "1000px"
}
const show = (params: { id?: string }) => {
  dialogFormRef.value.show()
  id.value = params?.id
  if (id.value) {
    nextTick(() => {
      getData()
    })
  }
}

/**
 * 获取数据
 */
const getData = async () => {
  const result = await processRequest.get("/api/CodeRule/Detail", {
    id: id.value
  }, {
    isLoading: true
  })
  formData.value = {
    ...result,
    items: result.codeRuleItemList
  }
}

/**
 * 主单数据
 */
const formData: any = ref({
  name: "",
  order: 0,
  symbol: "",
  items: [{}]
})

/**
 * 新增
 */
const handleAdd = () => {
  formData.value.items.push({})
}

/**
 * 删除
 */
const handleDelete = async (index: number) => {
  await ElMessageBox.confirm("是否确认删除？", "删除", {
    type: "warning"
  })
  formData.value.items.splice(index, 1)
}

/**
 * 构建预览数据
 */
const previewData = ref()
const previewTemplate = ref()
const constructionPreviewData = (data: any) => {
  previewTemplate.value = ""
  const templateList: any = []
  const list = data.items.map((item: any) => {
    templateList.push(item.codeType == null ? "" : CodeTypeEnum[item.codeType])
    if (item.codeType === CodeTypeEnum['常量']) {
      return item.constant || ""
    } else if (item.codeType === CodeTypeEnum['时间']) {
      if (!item.dateType) {
        return false
      }
      if (item.dateType === DateTypeEnum['年']) {
        return new Date().getFullYear().toString()
      } else if (item.dateType === DateTypeEnum['年月']) {
        return new Date().getFullYear().toString() + "/" + new Date().getMonth().toString()
      } else if (item.dateType === DateTypeEnum['年月日']) {
        return new Date().getFullYear().toString() + "/" + new Date().getMonth().toString() + "/" + new Date().getDate().toString()
      } else if (item.dateType === DateTypeEnum['月日']) {
        return new Date().getMonth().toString() + "/" + new Date().getDate().toString()
      }
    } else if (item.codeType === CodeTypeEnum['流水号']) {
      if (item.initSerialNumber && item.serialLength) {
        let num: string = ""
        for (let i = 0; i < item.serialLength - 1; i++) {
          num += "0"
        }
        return num + item.initSerialNumber
      } else {
        return item.initSerialNumber || "1"
      }
    }
  })
  previewData.value = list.join(data.symbol || "")
  previewTemplate.value = templateList.join(data.symbol || "")
}

/**
 * 监听
 */
watch(() => formData.value, (newValue: any) => {
  if (newValue) {
    constructionPreviewData(newValue)
  }
}, {
  deep: true
})

/**
 * 取消
 */
const handleClose = () => {
  dialogFormRef.value.close()
}

/**
 * 提交
 */
const handleSubmit = async () => {
  await ElMessageBox.confirm("是否确认提交编码规则？", "编码规则", {
    type: "warning"
  })

  const item = formData.value.items.map((item: any, index: number) => {
    return {
      ...item,
      order: index
    }
  })

  if (id.value) {
    await processRequest.put("/api/CodeRule", {
      ...formData.value,
      items: item
    }, {
      isLoading: true
    })
    ElMessage.success("编辑成功")
  } else {
    await processRequest.post("/api/CodeRule", {
      ...formData.value,
      items: item
    }, {
      isLoading: true
    })
    ElMessage.success("新增成功")
  }
  emit("confirm")
  handleClose()
}

/**
 * 暴露
 */
defineExpose({
  show
})
</script>

<template>
  <DialogForm ref="dialogFormRef" :dialogFormModel="dialogFormModel">
    <div class="order-form">
      <div class="form-header">
        <div class="header-title">{{ previewData || "-" }}</div>
        <div class="header-content">{{ previewTemplate || "-" }}</div>
      </div>
      <div class="form-body">
        <div class="form-body-item">
          <div class="label">
            编码规则名称：
          </div>
          <el-input v-model="formData.name" clearable placeholder="编码规则名称" style="width: 200px"/>
        </div>
        <div class="form-body-item">
          <div class="label">
            序号：
          </div>
          <el-input-number v-model="formData.order" min="0" placeholder="序号"/>
        </div>
        <div class="form-body-item">
          <div class="label">
            分隔符：
          </div>
          <el-input v-model="formData.symbol" clearable placeholder="分隔符" style="width: 200px"/>
        </div>
      </div>
      <div class="form-footer">
        <div class="form-footer-program">
          <div class="program-item">
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </div>
        </div>
        <el-scrollbar>
          <div class="form-footer-list">
            <div v-for="(item,index) in formData.items" :key="index" class="item">
              <div class="item-form">
                <div class="item-form-item">
                  <div class="label">
                    编码{{ index + 1 }}段
                  </div>
                  <el-select v-model="item['codeType']" clearable filterable placeholder="编码类型">
                    <el-option v-for="optionItem in convertEnumToList(CodeTypeEnum)" :key="optionItem.value"
                               :label="optionItem.label" :value="optionItem.value"></el-option>
                  </el-select>
                </div>
                <div v-if="item['codeType'] === CodeTypeEnum['常量']" class="item-form-item">
                  <div class="label">
                    常量值
                  </div>
                  <el-input v-model="item['constant']" clearable placeholder="常量值"></el-input>
                </div>
                <div v-if="item['codeType'] === CodeTypeEnum['时间']" class="item-form-item">
                  <div class="label">
                    时间类型
                  </div>
                  <el-select v-model="item['dateType']" clearable filterable placeholder="时间类型">
                    <el-option v-for="optionItem in convertEnumToList(DateTypeEnum)" :key="optionItem.value"
                               :label="optionItem.label" :value="optionItem.value"></el-option>
                  </el-select>
                </div>
                <div v-if="item['codeType'] === CodeTypeEnum['流水号']" class="item-form-item">
                  <div class="label">
                    流水号初始值
                  </div>
                  <el-input-number v-model="item['initSerialNumber']" :min="0" clearable placeholder="流水号初始值"
                                   style="width: 230px"></el-input-number>
                </div>
                <div v-if="item['codeType'] === CodeTypeEnum['流水号']" class="item-form-item">
                  <div class="label">
                    流水号长度
                  </div>
                  <el-input-number v-model="item['serialLength']" :min="1" clearable placeholder="流水号长度"
                                   style="width: 230px"></el-input-number>
                </div>
                <div v-if="item['codeType'] === CodeTypeEnum['流水号']" class="item-form-item">
                  <div class="label">
                    流水号刷新规则
                  </div>
                  <el-select v-model="item['serialRefreshDateType']" clearable filterable placeholder="流水号刷新规则">
                    <el-option v-for="optionItem in convertEnumToList(RefreshDateTypeEnum)" :key="optionItem.value"
                               :label="optionItem.label" :value="optionItem.value"></el-option>
                  </el-select>
                </div>
              </div>
              {{ item.index }}
              <div class="item-delete" @click="handleDelete(index)">
                <!--                  <img src="" alt="" class="item-delete-icon" />-->
                <div class="item-delete-content">
                  删除
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <div class="form-btn">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </div>
  </DialogForm>
</template>

<style lang="scss" scoped>
.order-form {

  .form-header {
    text-align: center;

    .header-title {
      font-size: 24px;
    }

    .header-content {
      margin-top: 5px;
      font-size: 16px;
      color: #999999;
    }
  }

  .form-body {
    margin-top: 30px;
    display: flex;
    gap: 30px;
    justify-content: center;

    .form-body-item {
      white-space: nowrap;
      display: flex;
      align-items: center;

      .label {
        font-size: 16px;
      }
    }
  }

  .form-footer {
    margin-top: 30px;
    min-height: 430px;

    .form-footer-list {
      margin-top: 20px;
      display: flex;
      gap: 30px;

      .item {
        box-sizing: border-box;
        border-radius: 10px;
        min-height: 380px;
        min-width: 270px;
        background: #f7f7f7;
        display: flex;
        flex-direction: column;

        .item-form {
          padding: 20px 20px 0 20px;
          flex: 1;

          .item-form-item {
            margin-bottom: 10px;

            .label {
              font-size: 14px;
              margin-bottom: 3px;
            }
          }
        }

        .item-delete {
          flex: 0;
          flex-basis: 30px;
          background: #F56C6C;
          display: flex;
          justify-content: center;
          border-radius: 0 0 10px 10px;

          .item-delete-content {
            line-height: 30px;
            color: #efefef;
          }
        }
      }
    }
  }

  .form-btn {
    display: flex;
    justify-content: center;
    gap: 30px;
    margin-top: 20px;
  }
}
</style>